package com.hongxun.design.ui.dragview;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.DragEvent;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.lang.ref.WeakReference;
import java.util.List;

import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.adapters.PhotoPassGridAdapter;
import com.hongxun.design.bean.PhotoPassagewayBean;
import com.hongxun.design.bean.PhotoPassagewayItemBean;
import com.hongxun.design.constant.Constant;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.ui.dragview.gridview_custom.DragGridView;
import com.hongxun.design.utils.imageutil.UriUtil;

import com.facebook.drawee.view.SimpleDraweeView;

/**
 * Created by zerdoor_pc on 2016/5/13.
 */
@SuppressLint("NewApi")
public class MyPassagewayDragView extends RelativeLayout {
    private HorizontalScrollView hscroll;
    private LinearLayout add;
    private TextView bleft, add_no, bright;
    private View line;
    private DragGridView grid;
    private PhotoPassagewayBean bean;
    PhotoPassagewayItemBean itemBean;
    SimpleDraweeView move;
    private Context context;
    MyPassagewayDragView _root;
    RelativeLayout addimage;

    private int minX = 0;
    private int maxX = 0;
    public static float Level = (float) 1.0;
    private float distance = 0;

    private int ViewY = 0;

    public MyPassagewayDragView(Context context) {
        super(context);
        this.context = context;
        _root = this;
    }

    public MyPassagewayDragView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        _root = this;
    }

    public MyPassagewayDragView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        _root = this;
    }


    @Override
    protected void onFinishInflate() {
        /**头部图标**/
        hscroll = (HorizontalScrollView) findViewById(R.id.passageway_hscroll);
        add = (LinearLayout) findViewById(R.id.passageway_add);
        add_no = (TextView) findViewById(R.id.passageway_add_no);
        add_no.setVisibility(GONE);
        /**中部布局**/
        bleft = (TextView) findViewById(R.id.passageway_bleft);
        bright = (TextView) findViewById(R.id.passageway_bright);
        line = findViewById(R.id.passageway_line);
        addimage = (RelativeLayout) findViewById(R.id.passageway_addimage);
        /**下方工具栏**/
        grid = (DragGridView) findViewById(R.id.passageway_grid);
        move = (SimpleDraweeView) findViewById(R.id.move_icon);

        super.onFinishInflate();
    }

    int[] s;
    boolean Drag = true;

    public void setData(PhotoPassagewayBean bean, boolean Drag) {
        if (MyApp.ReadOnly) {
            Drag=false;
        }
            this.Drag = Drag;
            if (bean == null) return;
            this.bean = bean;
            //setLevel();
            setHscroll(bean.getScrollData());
            setGrid(bean.getGridData());

    }

    /**
     * 加载已选订控件*
     */
    public void addViews(List<PhotoPassagewayItemBean> data) {
        if (Level <= 1) setLevel();
        if (maxX <= 0) setLevel();
        if (data.size() == 0) return;
        for (PhotoPassagewayItemBean passagewayItemBean : data) {
            AddDragIcon dragIcon = new AddDragIcon();
            int viewx = (int) (Float.parseFloat(passagewayItemBean.distance) / Level);
            MyLog.L(MString.SUCCESSED + "  viewx=" + viewx);
            MyLog.L(MString.SUCCESSED + "  distance=" + passagewayItemBean.distance);
            MyLog.L(MString.SUCCESSED + "  this.distance=" + distance);
            MyLog.L(MString.SUCCESSED + "  Level=" + Level);
            MyLog.L(MString.SUCCESSED + "===================================");
            passagewayItemBean.setXy(new int[]{viewx, ViewY});
            dragIcon.setData(passagewayItemBean, context, addimage, Constant.TYPE_ADD);
        }

    }

    /**
     * 设置比例尺*
     */
    public void setLevel() {
        //addimage.addView(new View(context));



        s = new int[2];
        line.getLocationOnScreen(s);
       // MyLog.L(MString.SUCCESSED + "s[0]=" + s[0] + "s[1]=" + s[1]+" Width="+line.getMeasuredWidth());
        if (line.getWidth()==0){
            float  width=((Activity)context).getWindowManager().getDefaultDisplay().getWidth();
            maxX = (int) (width*4/5 - 20);
        }else{
            maxX = line.getWidth() - 20;
        }
        ViewY = s[1];
        MyLog.L(MString.SUCCESSED + "distance=" + distance);
        MyLog.L(MString.SUCCESSED + "maxX=" + maxX);
        MyLog.L(MString.SUCCESSED + "minX=" + minX);
        if (maxX > 0) {
            Level = distance / (float) (maxX - minX);
        }
        grid.setLevel(Level);
        MyLog.L(MString.SUCCESSED + "Level=" + Level);

    }

    /**
     * 设置实际最大距离*
     */
    public void setDistance(float distance) {
        this.distance = distance;
        setLevel();
//        this.distance = 800;
    }

    private void setGrid(List<PhotoPassagewayItemBean> gridBean) {
        if (gridBean == null) return;
        PhotoPassGridAdapter adapter = new PhotoPassGridAdapter(gridBean, context);
        grid.setAdapter(adapter);
        grid.setLine(addimage, addimage, ViewY, Drag);
    }


    private void setHscroll(List<PhotoPassagewayItemBean> Scrollbean) {
        if (Scrollbean == null || Scrollbean.size() == 0) {
            add_no.setVisibility(VISIBLE);
            add_no.setText(R.string.no_point_data);
            return;
        } else {
            add_no.setVisibility(GONE);
        }
        int num = Scrollbean.size();
        if (Drag) {
            mGestureDetector = new GestureDetector(context, new DrapGestureListener());//添加长按监听器
        }
        for (int i = 0; i < num; i++) {
            addViewFormLinearLayout(i, Scrollbean.get(i));
        }
    }

    /**
     * 加载上部图标*
     */

    private void addViewFormLinearLayout(int i, PhotoPassagewayItemBean itemBean) {
        RelativeLayout layout = new RelativeLayout(context);
        ImageTextItem view = new ImageTextItem(context);
//        view.setIcon(itemBean.getUrl());
//        view.setName(itemBean.getName());
//        view.setValue(itemBean.getValue(), View.VISIBLE);
//        view.setIconTouch(itemBean.getUrlSeleck());
        view.setData(itemBean, VISIBLE);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.CENTER_IN_PARENT);
        layout.addView(view, params);
        final float scale = context.getResources().getDisplayMetrics().density;
        int left = (int) (15 * scale + 0.5f);
        layout.setPadding(left, 0, left, 0);
        add.addView(layout, RelativeLayout.LayoutParams.WRAP_CONTENT, add.getHeight() - 4);
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        layout.measure(w, h);
        layout.setTag(i);
        if (Drag) {
            view.setOnTouchListener(mOnTouchListener);
            addimage.setOnDragListener(mOnDragListener);
        }
    }

    public void setLeft(String value, OnClickListener listener) {
        if (bleft != null) {
            bleft.setText(value);
            bleft.setOnClickListener(listener);
        }
    }

    public void setRight(String value, OnClickListener listener) {
        if (bright != null) {
            bright.setText(value);
            bright.setOnClickListener(listener);
        }
    }


    private View mDrapView;
    private GestureDetector mGestureDetector;


    private OnTouchListener mOnTouchListener = new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            mDrapView = v;

            if (mGestureDetector.onTouchEvent(event))
                return true;


            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_UP:

                    break;
            }

            return false;
        }
    };

    private OnDragListener mOnDragListener = new OnDragListener() {
        boolean flag = true;

        @SuppressLint("NewApi")
        @Override
        public boolean onDrag(View v, DragEvent event) {
            switch (event.getAction()) {
                case DragEvent.ACTION_DRAG_STARTED:
                    // Do nothing
                    move.setVisibility(GONE);
                    break;
                case DragEvent.ACTION_DRAG_ENTERED:
                    break;
                case DragEvent.ACTION_DRAG_EXITED:

                    break;
                case DragEvent.ACTION_DROP:
                    if (s == null) {
                        s = new int[2];
                        line.getLocationOnScreen(s);
                    }
                    int[] s2 = new int[2];
                    v.getLocationOnScreen(s2);
                    s2[0] = (int) (event.getX());
                    if (!(s2[0] + v.getWidth() < s[0] || s2[0] > s[0] + line.getWidth())) {
                        itemBean.setXy(new int[]{s2[0], ViewY});
//                        MyLog.L("passway距离=getXy:" + JSON.toJSONString(itemBean.getXy()));
//                        MyLog.L("passway距离=s:" + JSON.toJSONString(s));
//                        MyLog.L("passway距离=s2:" + JSON.toJSONString(s2));
//                        MyLog.L("passway距离=line:" + (s[0] + line.getWidth()));
                        itemBean.setDistance((s2[0] * Level) + "");
                        AddDragIcon dragIcon = new AddDragIcon();
                        dragIcon.setData(itemBean, context, addimage, Constant.TYPE_TOP);

                    }
                    break;
                case DragEvent.ACTION_DRAG_ENDED:
                    break;

                default:
                    break;
            }
            return true;
        }
    };


    private WindowManager mWindowManager;

    private class DrapGestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            return super.onSingleTapConfirmed(e);
        }

        @Override
        public void onShowPress(MotionEvent e) {


            ImageTextItem view = (ImageTextItem) mDrapView;
            PhotoPassagewayItemBean bean = view.getItemBean();

            ClipData data = ClipData.newRawUri("", UriUtil.getUri(bean.getUrlSeleck()));
            MyDragShadowBuilder shadowBuilder = new MyDragShadowBuilder(
                    move);
            move.setImageURI(UriUtil.getUri(bean.getUrlSeleck()));
            itemBean = bean;
            move.setVisibility(VISIBLE);


            move.startDrag(data, shadowBuilder, move, 0);
            super.onShowPress(e);

        }

        @Override
        public void onLongPress(MotionEvent e) {
            super.onLongPress(e);

        }

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }
    }

    private class MyDragShadowBuilder extends View.DragShadowBuilder {

        private final WeakReference<View> mView;

        public MyDragShadowBuilder(View view) {
            super(view);
            mView = new WeakReference<View>(view);
        }

        @Override
        public void onDrawShadow(Canvas canvas) {
            canvas.scale(1.5F, 1.5F);
            super.onDrawShadow(canvas);
        }

        @Override
        public void onProvideShadowMetrics(Point shadowSize,
                                           Point shadowTouchPoint) {
            // super.onProvideShadowMetrics(shadowSize, shadowTouchPoint);

            final View view = mView.get();
            if (view != null) {
                shadowSize.set((int) (view.getWidth() * 1.5F),
                        (int) (view.getHeight() * 1.5F));
                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
            } else {
                // Log.e(View.VIEW_LOG_TAG,
                // "Asked for drag thumb metrics but no view");
            }
        }
    }
}


//
//        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
//        mStatusHeight = getStatusHeight(context);

//        grid.setOnTouchListener(new OnTouchListener() {
//            int startX;
//            int startY;
//
//            @Override
//            public boolean onTouch(View view, MotionEvent ev) {
//
//                switch (ev.getAction()) {
//                    case MotionEvent.ACTION_DOWN:
//                        int y = (int) ev.getRawY();
//                        int x = (int) ev.getRawX();
//                        mDownX = (int) ev.getX();
//                        mDownY = (int) ev.getY();
//                        mDragPosition = grid.pointToPosition(mDownX, mDownY);
//                        MyLog.L("触摸grid:mDragPosition=" + mDragPosition);
//                        MyLog.L("触摸grid:y=" + y);
//                        MyLog.L("触摸grid:x=" + x);
//                        MyLog.L("触摸grid:mDownX=" + mDownX);
//                        MyLog.L("触摸grid:mDownY=" + mDownY);
//                        if (mDragPosition == AdapterView.INVALID_POSITION) {
//                            return false;
//                        }
//                        ImageTextItem item = (ImageTextItem) grid.getChildAt(mDragPosition);
//                        MyLog.L("触摸grid:item=" + item);
//                        MyLog.L("触摸grid:item=" + grid.getChildAt(mDragPosition));
//                        if (item != null) {
//                            iconUrl = item.getIconTouch();
//                            MyLog.L("触摸grid:iconUrl=" + iconUrl);
//
//
////                            mWindowLayoutParams = new WindowManager.LayoutParams();
////                            mWindowLayoutParams.format = PixelFormat.TRANSLUCENT;
////                            mWindowLayoutParams.gravity = Gravity.TOP | Gravity.LEFT;
////                            mWindowLayoutParams.x = mDownX - mPoint2ItemLeft + mOffset2Left;
////                            mWindowLayoutParams.y = mDownY - mPoint2ItemTop + mOffset2Top - mStatusHeight;
////                            mWindowLayoutParams.alpha = 0.55f;
////                            mWindowLayoutParams.width = move.getLayoutParams().width;
////                            mWindowLayoutParams.height = move.getLayoutParams().height;
////                            mWindowLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
////                                    | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
////                            MarginLayoutParams margin=new MarginLayoutParams(move.getLayoutParams());
////                            margin.setMargins(x,y, x+margin.width, y+margin.bottomMargin);
////                            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(margin);
//
//                            move.setY(0);
//                            move.setX(0);
//                            move.setImageURI(UriUtil.getUri(iconUrl));
//                            move.setVisibility(VISIBLE);
//                            int[] location2 = new int[2];
//                            move.getLocationOnScreen(location2);
//
//
//                            int[] location = new int[2];
//                            view.getLocationOnScreen(location);
//                            move.setX(location[0]+mDownX);
//                            move.setY(location[1]-location2[1]+mDownY-10);
//
//                            MyLog.L("触摸grid:layout= " +JSON.toJSONString(location));
//
////                            mWindowManager.addView(move,mWindowLayoutParams);
////                            MyLog.L("触摸grid:layout=mDownX：" + startX+" mDownY："+startY);
////                            MyLog.L("触摸grid:layout=l：" + l+" r："+r+" t："+t+" b："+b);
////                            MyLog.L("触摸grid:layout=newl：" + newl+" newt："+newt+" newr："+newr+" newb："+newb);
////                            move.layout(newl, newt, newr, newb);
//                            DragUtil dragUtil = new DragUtil(context, move);//设置拖拽属性
//                            dragUtil.setDrag();
//
//
//                        }
//                        break;
//                    case MotionEvent.ACTION_MOVE:
//                        break;
//                    case MotionEvent.ACTION_UP:
//                        break;
//                }
//                return false;
//            }
//        });